﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Markup;
using System.Security.Principal;
using System.Windows.Resources;
using System.Collections;
using System.ComponentModel;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using CMD_DKT.Synchronization; 
using CMD.BAL.MISC;
using CMD_DKT.Conf;
using CMD.BAL.MISC;
using System.DirectoryServices;
using eVentasUpdater;

namespace CMD_DKT
{
    /// <summary>
    /// Lógica de interacción para MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private SincronizaCatalogos SincCatalogos;
        private Sol.UISolicitudes Despliega;

        public Sol.UISolicitudes Despliega1
        {
            get { return Despliega; }
            set { Despliega = value; }
        }
        public DispatcherTimer dTimerClock;

        public MainWindow()
        {
            string nombreDBISMS;
           
            InitializeComponent();
            popMenu.IsOpen = false;
            scrollViewer1.Content = null;
            lblMenu.Content = "Solicitud Clientes";
            Despliega = new Sol.UISolicitudes(ctcSubmenus, ctcNavegacion, scrollViewer1);
            
            //******************* INI BZG *************************
            // Valida si existe archivo de catalogos nuevo para actuaizar
            SincCatalogos = new SincronizaCatalogos();
            string compartida = System.Configuration.ConfigurationManager.AppSettings["ServerDocsFolder"];
            if (SincCatalogos.ValidaActualizacionCatalogos(compartida))
            {
                WndSincCatalogos conf = new WndSincCatalogos(this);
                conf.ShowDialog();
            }
            //******************* FIN BZG *************************

            //Uri iconUri = new Uri("pack://application:,,,/WPFIcon2.ico", UriKind.RelativeOrAbsolute);
            //this.Icon = BitmapFrame.Create(iconUri);
            nombreDBISMS=System.Configuration.ConfigurationManager.AppSettings["IsmsDbName"];
            dTimerClock = new DispatcherTimer();
            dTimerClock.Tick += new EventHandler(dTimerClock_Tick);
            dTimerClock.Interval = new TimeSpan(0, 0, 1);
            dTimerClock.Start();

            string message = "";

            //if (CheckConn.checkSMS(nombreDBISMS, ref message) != 0)
            //{
            //    MessageBox.Show(message,"Atención",MessageBoxButton.OK,MessageBoxImage.Error);
            //    this.Close();
            //}
            CheckCurrentUserAccess();
            verificarStatusImgConn();
        }


       //Label que imprime el usuario
        private void label1_Loaded(object sender, RoutedEventArgs e)
        {
            string struser = null;
            System.Security.Principal.WindowsIdentity user = System.Security.Principal.WindowsIdentity.GetCurrent();
            struser = user.Name;
            lblUsuario.Content =struser;

        }

      //Label Menú principal
        private void label2_MouseUp(object sender, MouseButtonEventArgs e)
        {            
            popMenu.PlacementTarget = this.lblMenu;
            popMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
            popMenu.IsOpen = true;
        }

        //---- Evento realizado al hacer clic en el menú principal "Solicitud Clientes" ----//
        public void lblSolicitudClientes_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (Despliega1 !=null && Despliega1.Alta != null && Despliega1.Alta.SolicitudDocs != "-1")
                if (Despliega1.Alta.ValidarCerradoSolicitud())
                {
                    popMenu.IsOpen = false;
                    scrollViewer1.Content = null;
                    lblMenu.Content = "Solicitud Clientes";
                    Despliega1 = new Sol.UISolicitudes(ctcSubmenus, ctcNavegacion, scrollViewer1);
                    return;
                }
                else
                    return;

            if (Despliega1 != null && Despliega1.Reemplazos != null && Despliega1.Reemplazos.SolicitudDocs != "-1")
                if (Despliega1.Reemplazos.ValidarCerradoSolicitud())
                {
                    popMenu.IsOpen = false;
                    scrollViewer1.Content = null;
                    lblMenu.Content = "Solicitud Clientes";
                    Despliega1 = new Sol.UISolicitudes(ctcSubmenus, ctcNavegacion, scrollViewer1);
                    return;
                }
                else
                    return;

            if (Despliega1 != null && Despliega1.Modificaciones != null && Despliega1.Modificaciones.SolicitudDocs != "-1")
                if (Despliega1.Modificaciones.ValidarCerradoSolicitud())
                {
                    popMenu.IsOpen = false;
                    scrollViewer1.Content = null;
                    lblMenu.Content = "Solicitud Clientes";
                    Despliega1 = new Sol.UISolicitudes(ctcSubmenus, ctcNavegacion, scrollViewer1);
                    return;
                }

            popMenu.IsOpen = false;
            scrollViewer1.Content = null;
            lblMenu.Content = "Solicitud Clientes";
            Despliega1 = new Sol.UISolicitudes(ctcSubmenus, ctcNavegacion, scrollViewer1);
            return;
                       
        }
             
        #region FormatoEtiquetasNavegacion

        private void lbTodas_MouseUp(object sender, MouseButtonEventArgs e)
        {
           
         }

        private void lbAltas_MouseUp(object sender, MouseButtonEventArgs e)
        {
            
        }

        private void lbModificaciones_MouseUp(object sender, MouseButtonEventArgs e)
        {
        }

        private void lbReemplazos_MouseUp(object sender, MouseButtonEventArgs e)
        {
            
        }

        private void lbAprobadas_MouseUp(object sender, MouseButtonEventArgs e)
        {
           
        }

        private void lbBorradores_MouseUp(object sender, MouseButtonEventArgs e)
        {
            
        }

        #endregion

    
        //---- Evento al hacer clic en la opción "Configuración" del menú principal ------ // 
        private void lblConfiguracion_MouseUp(object sender, MouseButtonEventArgs e)
        {
            //popMenu.IsOpen = false;
            //lblMenu.Content = "Configuración";
            //ctcSubmenus.Content = null;
            //ctcNavegacion.Content = null;
            Conf.WndConfig wndConfig = new Conf.WndConfig();
            wndConfig.Owner = this;
            wndConfig.ShowDialog();
        }
        
        private void tbkCancelar_MouseUP(object sender, MouseEventArgs e)
        {
        }

        private void scrollViewer1_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
        }

        void DataWindow_Closing(object sender, CancelEventArgs e)
        {
            if(Despliega1 !=null  && Despliega1.Alta!=null && Despliega1.Alta.SolicitudDocs!="")
                e.Cancel = !Despliega1.Alta.ValidarCerradoSolicitud();
            if (Despliega1 != null && Despliega1.Reemplazos != null && Despliega1.Reemplazos.SolicitudDocs != "")
                e.Cancel = !Despliega1.Reemplazos.ValidarCerradoSolicitud();
            if (Despliega1 != null && Despliega1.Modificaciones != null && Despliega1.Modificaciones.SolicitudDocs != "")
                e.Cancel = !Despliega1.Modificaciones.ValidarCerradoSolicitud();

            Application.Current.Shutdown();

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }

        private void StackPanel_MouseUp(object sender, MouseButtonEventArgs e)
        {

        }
        private void spConfigBtn_MouseUp(object sender, MouseButtonEventArgs e)
        {
            Conf.WndConfig wndConfig = new Conf.WndConfig();
            wndConfig.Owner = this;
            wndConfig.ShowDialog();
        }

        private void brdBrnSinc_MouseUp(object sender, MouseButtonEventArgs e)
        {
            Storyboard sb = (Storyboard)Application.Current.FindResource("rotateImg");
            //sb.Begin(this);

            MainWindow mw = (MainWindow)App.Current.MainWindow;

            System.Windows.Threading.DispatcherOperation op2 = mw.Dispatcher.BeginInvoke(
                DispatcherPriority.Normal, new Action(() =>
           Sync.start(sb, this)));

            WndConfig conf = new WndConfig();
            conf.btnRevisarStatus_Click(null, null);

            if (Despliega1 != null)
                Despliega1.RefreshContadores();
        }


        void dTimerClock_Tick(object sender, EventArgs e)
        {
            ((DispatcherTimer)sender).Interval = AppConfs.tsTimer;

            Storyboard sb = (Storyboard)Application.Current.Windows[0].FindResource("rotateImg");
            WndConfig conf= new WndConfig();
            MainWindow mw = (MainWindow)App.Current.MainWindow;

            new System.Threading.Thread(delegate()
            {
                Sync.start(sb, mw);
            }).Start();

            conf.btnRevisarStatus_Click(null, null);

            if (Despliega1 != null)
                Despliega1.RefreshContadores();

            verificarStatusImgConn();
        }

        public void BloqueoMenus(bool enable)
        {
            ctcSubmenus.IsEnabled = enable;
            ctcSubmenus.Opacity = (enable) ? 1.0 : 0.5;
            lblMenu.IsEnabled = enable;
            lblMenu.Opacity = (enable) ? 1.0 : 0.5;
        }

        public void verificarStatusImgConn()
        {
            MainWindow mw = (MainWindow)App.Current.MainWindow;
            string[] statusConn = Utilities.Utilities.CheckPathAccess(AppConfs.ServerDocsFolder,false);
            BitmapImage bi1 = new BitmapImage();
            string simgs;
            bi1.CacheOption = BitmapCacheOption.OnLoad;
            bi1.BeginInit();
            if (statusConn[0] == "1" && Utilities.Utilities.checkPathToWrite(AppConfs.ServerDocsFolder))
            {
                simgs = "Images/main_btn_wifi_green.png";
                mw.Despliega1.CorreoUsuario = CMD_DKT.Utilities.CMDInfo.GetEmailUser();
            }
            else
                simgs = "Images/main_btn_wifi_red.png";
            bi1.UriSource = new Uri(simgs, UriKind.Relative);
            bi1.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            bi1.EndInit();
            img_statusConn.Source = bi1;
        }
        
            private static void CheckCurrentUserAccess()
            {
                try
                {
                    Boolean TienePermiso=false;
                    System.Security.Principal.WindowsIdentity usuario = System.Security.Principal.WindowsIdentity.GetCurrent();
                    IdentityReferenceCollection irc = usuario.Groups;
                    //string[] grupos = new string[irc.Count];
                    int i=0;
                    Dictionary<string,string>grupos= new Dictionary<string,string>();
                    foreach (IdentityReference ir in irc.Translate(typeof(NTAccount)))
                    {
                        string tmp = ir.Value.ToString();
                        if (tmp.Split('\\').Length > 1)
                            grupos.Add(tmp.Split('\\').Last().ToString(),i.ToString());
                        else
                            grupos.Add(tmp,i.ToString());
                        i++;
                    }
                    string grupos_temp=System.Configuration.ConfigurationManager.AppSettings["AppGroups"].ToString();
                    string[] Grupos =grupos_temp.Split('|');
                    foreach (string str in Grupos)
	                {
		                if(grupos.Keys.Contains(str))
                            TienePermiso=true;
	                }

                    if (!TienePermiso)
                    {
                        throw new Exception("Usted no tiene los permisos para ejecutar esta aplicación");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Atención", MessageBoxButton.OK, MessageBoxImage.Stop);
                    UpdateProc.EndEVentasProcess();
                }
            }
    }
}

